package org.kolonitsky.translator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.MissingResourceException;
import java.util.Properties;

import static org.kolonitsky.translator.utils.UTFPropertiesSupport.loadProperties;
import static org.kolonitsky.translator.Settings.ENCODING;

/**
 * @author Alex.Kolonitsky
 */

public class Dictionary extends BaseTranslator implements TranslatorCache {

    protected static final Log LOG = LogFactory.getLog(Dictionary.class);

    public static final String DICTIONARY_BASE_NAME = "dictionary_%s.properties";

    private Properties properties;
    private final File dataDir;

    public Dictionary(File dataDir, Lang lang) {
        super(lang);
        this.dataDir = dataDir;
    }

    public void load() {
        FileInputStream is = null;
        try {
            is = new FileInputStream(dataDir + File.separator + getFileName());
            this.properties = loadProperties(is, ENCODING);
        } catch (IOException e) {
            this.properties = new Properties();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();  // TODO
                }
            }
        }
    }

    public void save() {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(dataDir + File.separator + getFileName());
            this.properties.store(out, "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();  // TODO
                }
            }
        }
    }

    private String getFileName() {
        return String.format(DICTIONARY_BASE_NAME, to);
    }

    public String translate(String key) {
        try {
            return (String) properties.get(key);
        } catch (MissingResourceException e) {
            LOG.debug("Translation for '" + key + "' not found");
        }
        return null;
    }

    public void put(String key, String value) {
        properties.setProperty(key, value);
    }
}
